﻿using System;
using System.Configuration;
using ErrorDumper.Filtering;

namespace ErrorDumper.Configuration {
    public class FilteringConfigurationSection : ConfigurationSection, IExceptionFilter {
        private const string _sectionName = "errorDumper/filtering";

        public static FilteringConfigurationSection GetSection() {
            return (FilteringConfigurationSection)
                ConfigurationManager.GetSection(_sectionName);
        }

        [ConfigurationProperty("defaultLevel", IsRequired = false, DefaultValue = ExceptionHandlingLevel.WriteExtendedDump)]
        public ExceptionHandlingLevel DefaultLevel {
            get { return (ExceptionHandlingLevel)this["defaultLevel"]; }
            set { this["defaultLevel"] = value; }
        }

        [ConfigurationProperty("rules")]
        public FilterRuleConfigurationElementCollection Rules {
            get { return (FilterRuleConfigurationElementCollection)this["rules"]; }
        }

        internal ExceptionHandlingLevel GetLevelCore(ExceptionPropertyCollection properties) {
            var level = DefaultLevel;
            if (level == ExceptionHandlingLevel.Ignore)
                return ExceptionHandlingLevel.Ignore;

            if (properties != null)
                foreach (FilterRuleConfigurationElement entry in Rules)
                    if (entry.IsMatch(properties) &&
                        !ExceptionFilters.Resolve(ref level, entry.Mode))
                        return ExceptionHandlingLevel.Ignore;

            return level;
        }

        ExceptionHandlingLevel? IExceptionFilter.GetLevel(
            ExceptionPropertyCollection properties, Exception exception) {
            return GetLevelCore(properties);
        }

        ExceptionHandlingLevel? IExceptionFilter.GetLevel(
            ExceptionPropertyCollection properties, string content) {
            return GetLevelCore(properties);
        }
    }
}